from django import forms
from web.form.bootstrap import BootstrapForm
from web import models
from django.core.exceptions import ValidationError
from web.form.widgets import ColorRadioSelect


class projectModelForm(BootstrapForm, forms.ModelForm):
    # desc = forms.CharField(widget=forms.Textarea())
    bootstrap_class_exclude = ['color']

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'desc': forms.Textarea,
            'color': ColorRadioSelect(attrs={'class': 'color-radio'})
        }

    def clean_name(self):
        """项目进行校验"""
        name = self.cleaned_data['name']
        # 1 当前用户是否创建项目
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError("项目名已经存在")
        # 2 当前用户是否有额度创建
        # 最多创建多少项目
        self.request.tracer.price_policy.project_num
        # 现在创建了多少项目
        cout = models.Project.objects.filter(creator=self.request.tracer.user).count()

        if cout >= self.request.tracer.price_policy.project_num:
            raise ValidationError("项目已经超限，请购买套餐")
        return name
